﻿using System.Collections.Generic;
using System.Linq;

namespace KingerRobot.MexicoSailunMDC.Dao;
public static class LocHelper
{
    private static List<PORcsLocation> s_Locations { get; } = new List<PORcsLocation>();

    static LocHelper()
    {
        s_Locations = Db.Default.RcsLocations.ToList();
    }

    public static int GetPlcDestination(long locId)
    {
        var location = GetById(locId);
        if (int.TryParse(location.PlcCode, out var plcCode))
        {
            return plcCode;
        }

        throw new Exception($"Id为{locId}的位置plcCode的值{location.PlcCode}不是整数");
    }

    public static List<PORcsLocation> GetAll()
    {
        return s_Locations;
    }

    public static PORcsLocation GetById(long locId)
    {
        var location = s_Locations.FirstOrDefault(item => item.Id == locId);
        if (location == null)
        {
            throw new Exception($"缓存中未获取到Id为{locId}的位置信息");
        }
        return location;
    }

    public static PORcsLocation GetByIdSafe(long locId)
    {
        var location = s_Locations.FirstOrDefault(item => item.Id == locId);
        if (location == null)
        {
            return null;
        }
        return location;
    }

    public static string GetName(long? locId)
    {
        if (!locId.HasValue)
        {
            return null;
        }
        return s_Locations.FirstOrDefault(item => item.Id == locId)?.LocName;

    }

    public static PORcsLocation GetByName(string locName)
    {
        if (string.IsNullOrWhiteSpace(locName))
        {
            return null;
        }
        return s_Locations.FirstOrDefault(item => item.LocName == locName);

    }

    public static PORcsLocation GetByCode(string locCode)
    {
        if (string.IsNullOrWhiteSpace(locCode))
        {
            return null;
        }
        return s_Locations.FirstOrDefault(item => item.LocCode == locCode);

    }
    public static string GetCode(long? locId)
    {
        if (!locId.HasValue)
        {
            return null;
        }
        return s_Locations.FirstOrDefault(item => item.Id == locId)?.LocCode;

    }
}
